<?php require ('setcookie.html'); 
//this sets all variables, that are SUPPOSED TO BE USED FOR TEXT VISIBLE FOR USERS
//all text is encapsulated in the array-variable $LRV
//DO NOT set this variable yourself, if you want to change text, change right in language_related_variables 
require 'language_related_variables.php';

$language_decoder=array('de'=>"german", 'en'=>"english", 'es'=>"spanish", 'ru'=>"russian");
$url_part_array= explode(".", $_SERVER['SERVER_NAME']);
$site_language_short=$url_part_array[0];
if ($site_language_short == 'lingomoto') {$site_language_short = 'en';}
$site_language= $language_decoder[$site_language_short];
if (!$site_language){$site_language="german";$site_language_short="de";}
$LRV=filter_by_language($site_language);?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html lang="de">
<head>
    <title><?php print $LRV["title_tag"]["new_vocable_list"]?></title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="<?php print $LRV["description_meta_tag"]["new_vocable_list"]?>" />
    <meta name="language" content="de" />
    <link href="style.css" type="text/css" rel="stylesheet" />
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
</head>

<body id="trainer">
<?php
$_SESSION['logini'] = isset($_SESSION['logini']) ? $_SESSION['logini'] : false;
$box=($_REQUEST["box"]);


// read configuration
require $LRV["link_configuration"];
require $LRV["link_user"];

// read header
//print_r ($_REQUEST);
//variables that should be used in functions declared global
$customerid = $_SESSION['customerid'];
$username=get_username();
$lang_info=language_info($site_language_short);
$can_lang=$lang_info[0]; //'Deutsch' -> this is for the buttons  
$learn_lang=$lang_info[1];

$lang_info=language_info("en");
$can_lang_en=strtolower($lang_info[0]); //'german' -> this is used, when defining the table
$learn_lang_en=strtolower($lang_info[1]);

$langpair=$lang_info[2];

$box = isset($_REQUEST['box']) ? $_REQUEST['box'] : '1';

function get_username() //to fill the first edit field
{
   global $customerid;
   $res=mysql_query("SELECT username from customerdata where customerid=$customerid");	
   if ($res){
   $line=mysql_fetch_array($res);
   $username=$line[0];}
   return $username;

}

//functions for testing and error printing
function test_count()//this function you can use if you dont know where in the code your structure fails 
{
   global $count;
   $count++;
   print $count;b();
}

function b() {print '<br/>';} function n() {print "\n";} function bn() {print "<br/>\n";}

function mysql_query_secure($query)
{
   $result=mysql_query($query);
   if ( ! $result ) { die('Error query : ' . mysql_error()); }
   return $result;
}
function language_info($strTableEnding)
{
	   global $customerid;                     // ...de für deutsche Sprache
	   if (!$customerid) $customerid=-1;
	   $result = mysql_query_secure( "SELECT can$strTableEnding,learn$strTableEnding,langpair FROM settings where customerid = '$customerid'" );
	   if (mysql_num_rows($result)<>0) $line = mysql_fetch_array( $result, MYSQL_ASSOC);
	   return array($line['can'.$strTableEnding],$line['learn'.$strTableEnding],$line['langpair']);

}

function print_form() //1.page that is shown
{
	
global $link, $username, $can_lang, $learn_lang, $box,$LRV;

echo '<form name="xxx" action="'.$link.'" method="post" >';
echo $LRV["message_create_vocable_list_here_start"]; //depending on word order in different languages
//sometimes the select field comes last in the sentence, sometimes there is one word following
print ' <select name="box" >';
for ($intCount=1;$intCount<=6;$intCount++)
{
	if ($box == 'wordbox'.$intCount) $strSelectedTag= 'selected="selected"';
	else $strSelectedTag='';
	print '<option value="'.$intCount.'" '.$strSelectedTag.' >'.$LRV['first_box_title'].' '.$intCount.'</option>';
}
print '</select>';
echo $LRV["message_create_vocable_list_here_end"];

echo '   <p>';
echo '      '.$LRV["username"].': <b>'.$username . '</b>';b();
echo '      <input type="hidden" name="benutzer_name" value="'.$username.'">';
echo '      '.$LRV["known_language"].': <b>'.$can_lang . '</b>';b(); 
echo '      '.$LRV["learn_language"].': <b>'.$learn_lang . '</b>';b();
echo '      <span class="link"><a href="'.$LRV['link_settings'].'">'.$LRV["label_change_language"].'</a></span>'; b();
echo '		<br />';
echo '      '.$LRV["list_description"].' <input type="text" name="beschreibung" value="'.$_REQUEST['beschreibung'].'">';b();
echo '		<br />';
echo '      '.$LRV["message_insert_email_adresses"].':'; b();

echo '      <input type="text" name="email1" value="'.$_REQUEST['email1'].'">';b();
echo '      <input type="text" name="email2" value="'.$_REQUEST['email2'].'">';b();
echo '      <input type="text" name="email3" value="'.$_REQUEST['email3'].'">';b();
echo '      <input type="text" name="email4" value="'.$_REQUEST['email4'].'">';
echo '   </p>';
echo '		<br />';
echo '   <input type="submit" name="senden" value="'.$LRV['button_preview'].'" ';

//the page that the user clicked on "Vokabelliste bereitstellen" is saved to redirect him there when process is finished
//in the 1.call of the page, you find it in the official http_referer, for further calls it is saved in hidden variable "pre_page"
if ($_REQUEST['pre_page'])$referer=$_REQUEST['pre_page'];else $referer=$_SERVER["HTTP_REFERER"];

echo '   <input type="hidden" name="pre_page" value="'.$referer.'" ';
echo '	 <br /><br /><br />';
echo '   <div class="link"><a href="'.$referer.'">'.$LRV["link_back_to_lists"].'</a></div>';
echo '</form>';

}

function print_confirmation()//=preview
{
global $link, $username, $can_lang, $learn_lang,$langpair,$customerid,$box,$LRV;	
//print_r($_REQUEST);
echo $LRV["list_to_create"].':';
echo '<form name="xxx" action="'.$link.'" method="post" >';
echo '<p>';
echo $LRV["username"].': <b>'.$username . '</b>';b();
echo $LRV["known_language"].': <b>'.$can_lang . '</b>';b(); 
echo $LRV["learn_language"].': <b>'.$learn_lang . '</b>';b(); 
echo $LRV["list_description"].': <b>'. $_REQUEST['beschreibung'] . '</b>';b();b();
echo $LRV["emails_for_notification"].':';b();

//show and count all email adresses that had been filled in on 1.page
$email_count=1;
if ($_REQUEST['email1']) {echo $email_count.'.Email: '.$_REQUEST['email1'];b();$email_count+=1;}
if ($_REQUEST['email2']) {echo $email_count.'.Email: '.$_REQUEST['email2'];b();$email_count+=1;}
if ($_REQUEST['email3']) {echo $email_count.'.Email: '.$_REQUEST['email3'];b();$email_count+=1;}
if ($_REQUEST['email4']) {echo $email_count.'.Email: '.$_REQUEST['email4'];b();$email_count+=1;}
if ($email_count==1)  print $LRV["emails_none"];

echo '</p>';

//hidden values that might be needed if user wants to correct his filled in text -> no necessity to retype everything 
echo '<input type="hidden" name="benutzer_name" value="'.$username.'">';
echo '<input type="hidden" name="beschreibung" value="'.$_REQUEST['beschreibung'].'">';
echo '<input type="hidden" name="email1" value="'.$_REQUEST['email1'].'">';
echo '<input type="hidden" name="email2" value="'.$_REQUEST['email2'].'">';
echo '<input type="hidden" name="email3" value="'.$_REQUEST['email3'].'">';
echo '<input type="hidden" name="email4" value="'.$_REQUEST['email4'].'">';
b();
echo '<input type="submit" name="senden" value="'.$LRV["button_save_send"].'" ';b();
echo '<input type="submit" name="senden" value="'.$LRV["button_correct"].'" ';

echo '<input type="hidden" name="pre_page" value="'.$_REQUEST['pre_page'].'" ';
b();b();b();
echo $LRV["message_preview_20_vocables"].':';b();
b();
mysql_query("SET NAMES 'utf8'");
//getting words and translations
$query="SELECT 1art,1word,2art,2word,3art,3word,
	art1,word1,art2,word2,art3,word3 from wordbox0 where boxid=". $box . " AND customerid=$customerid AND langpairid=$langpair order by 1word,2word,3word LIMIT 0,20";
$res=mysql_query($query);

//showing values in table
echo '<table border="0" style="border-collapse:collapse">';
echo '<tr><th colspan ="6">'.$LRV["table_translation_titles"]["words"].'</th><th colspan ="6">'.
$LRV["table_translation_titles"]["translations"].'</th></tr>';
$dark_colour=True;
while ($row=mysql_fetch_array($res) and $count <20)
{
    
	$dark_colour=!$dark_colour;//every second row has a class that styles it darker... just for the looks of it
	//print_r($row);
	if ($dark_colour) {echo '<tr>'; } else { echo '<tr class="bg">'; }
	
	for($a=0;$a<=11; $a++)
	{
	    print "<td class='table6'>{$row[$a]}</td>";
	}
	print '</tr>';
}
print '</table>';
b();
echo '<input type="submit" name="senden" value="'.$LRV["button_save_send"].'" ';b();
echo '<input type="submit" name="senden" value="'.$LRV["button_correct"].'" ';

echo '<input type="hidden" name="pre_page" value="'.$_REQUEST['pre_page'].'" ';
echo '</form>';


//a second form because "abbrechen" goes back to the page where you clicked on "Vokabelliste bereitstellen"
echo '<form name="xxx" action="'.$_REQUEST['pre_page'].'" method="post" >';

echo '<input type="hidden" name="pre_page" value="'.$_REQUEST['pre_page'].'" ';
echo '<input type="submit" name="senden" value="'.$LRV["button_cancel"].'" ';
echo '</form>';

}

function validate_email()
{
	global $LRV;
    for ($count = 1; $count < 4; $count++)
    {
	$email=$_REQUEST["email$count"];
        if ($email)
        {
	     //print $email;

        $test_mail = filter_var($email, FILTER_VALIDATE_EMAIL);
        if ($test_mail === false)
        {
           echo "<div class='message'>$email ->".$LRV["error_email_format_incorrect"]."</div>"; 
           return false;
        }
        else
        {
    
         // 2. email-check
            $isValid = true;
            $isValid=validEmail($email);
    
            if ( $isValid == false )
            {
                echo "<div class='message'>$email ->".$LRV["error_email_format_incorrect"]."</div>";
		return false;

            }
            else
            {
    
                // spam-check
                tuersteher_zum_verstehen( $name );
                tuersteher_zum_verstehen( $email );
                
             } 
        }
	}
    }
    return true; 

}

function print_errors()
{
	global $LRV;
   if (!$_REQUEST['beschreibung'])print "<div class='message'>{$LRV["error_no_description"]}</div>";
  if (!$_REQUEST['benutzer_name'])print "<div class='message'>{$LRV["error_no_username"]}</div>";

}

function send_email($list_id) {

    global $email,$can_lang,$learn_lang,$LRV;
	
	ini_set("sendmail_from", "info@lingomoto.com");//this is important, because googlemail does not accept email if this is unset
	$name=$_REQUEST['benutzer_name'];
  for ($count=1; $count <=4; $count++)
  { 
  
  $receiver = $_REQUEST["email$count"];
  
    $sender   = "info@lingomoto.com"; 
    $subject  = $LRV["mail_message_vocablelist_recommended"];
    $replyto  = "info@lingomoto.com";
    $list_name=$_REQUEST['beschreibung'];  
    $mailtext = "$name {$LRV["mail_message_vocablelist_recommended_by"]}: $list_name
    
	{$LRV["known_language"]}: $can_lang
	{$LRV["learn_language"]}: $learn_lang
	
	{$LRV["link_view_list"]}&list_id1=$list_id";
	
    if ($receiver)
	{
	
         mail( $receiver,//$receiver,
        $subject, 
        $mailtext, "From: $sender ",
        "-f '$sender'");
	//mail( 'isabellknauer@googlemail.com','test','Hallo','From: info@lingomoto.com ',"-f 'info@lingomoto.com' ");
	}	
  }		
}

function tuersteher_zum_verstehen( $zum_testen )
{
    $uebeltaeter[] = '%0A';
    $uebeltaeter[] = 'to:';
    $uebeltaeter[] = 'cc:';
    $uebeltaeter[] = 'bcc:';
    $uebeltaeter[] = 'from:';
    $uebeltaeter[] = 'subject:';
    $uebeltaeter[] = 'reply-to:';
    $uebeltaeter[] = 'content-type:';
    $uebeltaeter[] = 'mime-version:';
    $uebeltaeter[] = 'multipart/mixed';
    $uebeltaeter[] = 'content-transfer-encoding:';
    foreach ($uebeltaeter AS $einzeltaeter )
    {
        if (eregi ($einzeltaeter, $zum_testen))
        {
            echo "<p>{$LRV["error_no_specialchars"]}</p>";
            // es wird also alles abgebrochen, wenn Gefahr in Verzug ist
            exit;
        }
    }
}

function validEmail($email)
{
   

   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
      (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))

      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

$link =$_SERVER['PHP_SELF'];
$langen = 'word-lists.html';
$langes = 'listas-vocablos.html';
$langru = 'word-lists.html';
$langde = 'vokabellisten.html';
require ($LRV["link_header"]);
// <!-- horizontal column -->
echo '<div>';
require ($LRV["link_horizontal"]);
echo '</div>';

// <!-- Left Column -->
echo '<div id="left_col">';
require ($LRV["link_vertical"]);
echo '</div>';

// <!-- Content -->
echo "<div id='content'>";
echo "<div id='block5'>";
if ($_REQUEST['pre_page'])$referer=$_REQUEST['pre_page'];else $referer=$_SERVER["HTTP_REFERER"];
//if (strpos($referer,$LRV['new_wordlist']))$referer=$LRV if i have some time...
/*print $_SESSION['logini'];
print $customerid;
print_r($_SESSION);*/
if (!$_SESSION['logini'] and ($customerid==-1)) {
    require_once ('loginformular.html'); 
//	print '<br/><p><a href="vokabellisten.html" class="lostpassword">Zurück zu den Listen</a></p>';
	echo '<br/><div class="link"><p><a href="'.$referer.'">'.$LRV["link_back_to_lists"].'</a></p></div>';
	
} 
else
{
echo "<h2>{$LRV["page_title"]["new_vocable_list"]}</h2>";
echo '<br />';

echo '<div class="content_frame">';
//echo '<div>Vokabellisten bereitstellen</div>';

if ($_REQUEST['senden']==$LRV["button_preview"])//user has clicked on preview in 1.page
{
   if 	($_REQUEST['beschreibung'] and $_REQUEST['benutzer_name'] and validate_email())
   {
       print_confirmation();	
   }
   else
   {
        print_errors();
        print_form();//1.page that is shown
   }
//   echo '</div>';
}
elseif ($_REQUEST['senden']=='' or $_REQUEST['senden']=='Korrigieren') print_form();
else //in the preview(2.page) the user has clicked on "Senden/Speichern"
{
    $list_name=$_REQUEST['beschreibung'];  
	//print $list_name;
    $user_name=$_REQUEST['benutzer_name'];
    
    //new vocable list in table created
    mysql_query ("INSERT INTO vocable_lists(langpair,listname,username,date,customerid)".
   " VALUES($langpair, '$list_name','$user_name',CURDATE(),$customerid) "); 
    
    //words and translations from wordbox(current box to learn) catched     
    $res=mysql_query("SELECT 1word,1art,2word,2art,3word,3art,
	word1,art1,word2,art2,word3,art3 from wordbox0 where boxid=". $box . " AND customerid=$customerid AND langpairid=$langpair");    
    
    $listid= mysql_insert_id();    //current list id
	 //new line in rating table
   $query="INSERT INTO ratings (listid,total_votes,total_value) VALUES ($listid,0,0)";
   
   mysql_query_secure($query);
    while ($row=mysql_fetch_array($res))
    {	  
          //for every line (word and translation) insert values in vocable_list_words
          mysql_query ("INSERT INTO vocable_lists_words (listid, 1word,1art,2word,2art,3word,3art,
	      word1,art1,word2,art2,word3,art3) VALUES".
          " ($listid,'{$row[0]}','{$row[1]}','{$row[2]}','{$row[3]}','{$row[4]}','{$row[5]}','{$row[6]}','{$row[7]}'
		  ,'{$row[8]}','{$row[9]}','{$row[10]}','{$row[11]}')");  
     }  
	 send_email($listid);
	 //user is redirected after 3 seconds to the page he came from (either vobable_lists or vocables_sort)
	 print '<meta http-equiv="refresh" content="3; URL='.$_REQUEST['pre_page'].'">';
     
     //user is informed about redirection and success of process 
     print "Vokabelliste $list_name erfolgreich bereitgestellt, Weiterleitung erfolgt."; 
}
   echo '</div>';
}

echo "</div>";

echo "</div>";
echo '<div id="adverts">';
echo '<div id="adbox"></div>';
echo '</div>';

require ($LRV["link_footer"]);
?>

</body>
</html>